import { defineStore } from 'pinia'

export const useLocationStore = defineStore('location', {
	state: () => {
		return {
			userLocation: {
				latitude: 0,
				longitude: 0
			}
		}
	},
	actions: {
		setUserLocation(location: { latitude: number, longitude: number }) {
			const { latitude, longitude } = location
			this.userLocation.latitude = Number(latitude)
			this.userLocation.longitude = Number(longitude)
		},
		refreshUserLocation(){
			return new Promise<{ latitude: number, longitude: number }>((reslove, reject) => {
				uni.getLocation({
					type: 'gcj02',
					success: (location) => {
						const { latitude, longitude } = location
						this.userLocation.latitude = Number(latitude)
						this.userLocation.longitude = Number(longitude)
						reslove(this.userLocation)
					},
					fail: (err) => {
						reject(err)
					}
				})
			})
		},
		hasUserLocation() {
			return this.userLocation.latitude && this.userLocation.longitude
		}
	}
})